package com.shockweb.common.calculate.function;

import java.math.BigDecimal;

import com.shockweb.common.calculate.CalculateException;
import com.shockweb.common.calculate.api.IFunction;

import java.util.List;

/**
 * 条件表达式
 * @author pengminghua
 *
 */
public class Iif implements IFunction{

	private static final BigDecimal zero = new BigDecimal(0);
	
	/**
	 * @see IFunction#eval(List)
	 */
	public Object eval(List<Object> params) throws CalculateException {
		try{
			BigDecimal cond = convert(params.get(0));
			Object value = null;
			if(cond.compareTo(zero)!=0){
				value = params.get(1);
			}else{
				value = params.get(2);
			}
			return value;
		}catch(Exception e){
			throw new CalculateException(e);
		}
	}
	 
	/**
	 * 鏁版嵁杞崲
	 * @param param
	 * @return
	 */
	private BigDecimal convert(Object param){
		BigDecimal value = null;
		if(param instanceof BigDecimal){
			value = (BigDecimal)param;
		}else{
			value = new BigDecimal((String)param);
		}
		return  value;
	}
	
	/**
	 * @see IFunction#getParamCount()
	 */
	public int getParamCount() {
		return 3;
	}
	
	/**
	 * @see IFunction#getName()
	 */
	public String getName() {
		return "iif";
	}
}
